import host
from host import host, host_dict
from ship import ship
from config import parse


class HostManage:
    def __init__(self) -> None:
        self.host_set = {}

    def install_host_to_all_ship(self, ship_list: dict):
        """给所有船只安装节点"""
        for s in ship_list.values():
            if isinstance(s, ship.Ship):
                # 获得船只名称
                ship_name = s.get_name()
                # 根据船只名称新建节点
                my_host = host.Host(ship_name)
                # 船只节点组
                host_group = s.get_host_group()
                # 给节点装载路由协议
                protocol = parse.Parse.get_router_by_ship_group(host_group)
                my_host.install_router(protocol, parse.Parse.get_single_host_by_ship_group(host_group))
                # 装入节点集
                self.host_set[ship_name] = my_host
                # 船只安装节点
                s.install_host(my_host)
        host_dict.HostDict.write(self.host_set)

    def setup_all_host(self):
        """启动节点开始工作"""
        for h in self.host_set.values():
            if isinstance(h, host.Host):
                h.start()

    # def register(self, host_name, my_host: host.Host):
    #     if self.host_set[host_name]:
    #         return False
    #     else:
    #         self.host_set[host_name] = my_host
    #         return True

    def get_host_by_name(self, host_name):
        host = self.host_set[host_name]
        if host:
            return host
        else:
            return None
